package com.example.homework08.sqliteroom;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import com.example.homework08.R;

import java.util.List;

public class SqliteRoomFragment extends Fragment {
    TextView textView;
    public SqliteRoomFragment(){
        super(R.layout.sqlite);
    }


    @Override
    public void onViewCreated(@NonNull View view, @NonNull Bundle savedInstanceState){
        super.onViewCreated(view, savedInstanceState);
        EditText et_name = getView().findViewById(R.id.et_name);
        EditText et_age = getView().findViewById(R.id.et_age);
        textView = getView().findViewById(R.id.tv_show);
        MyRoomDatabase db = MyRoomDatabase.getInstance(getActivity());

        getView().findViewById(R.id.add_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                db.userDao().insert(new User(et_name.getText().toString(),
                        Integer.parseInt(et_age.getText().toString())));

            }
        });

        getView().findViewById(R.id.ageless18_btn).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showUsers(db.userDao().searchUsersByAge(18));
                    }
                });

    }

    private void showUsers(List<User> users) {
        StringBuilder stringBuilder = new StringBuilder();
        for (User user : users) {
            stringBuilder.append("id: ").append(user.id)
                    .append("  username:  ").append(user.username)
                    .append(" age:  ").append(user.age)
                    .append("\n");
        }
//        TextView textView = getView().findViewById(R.id.tv_show);
        textView.setText(stringBuilder.toString());
    }


}
